package xyz.labmem.base.sys.aop

import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import xyz.labmem.base.core.consts.AopSortConstant
import xyz.labmem.base.core.consts.log
import xyz.labmem.base.core.tool.getIp
import java.util.*

/**
 * 以ApiOperation为切入注入用户信息
 * @Author lty
 * @Date 2021/12/15 15:01
 */
@Aspect
@Component
@Order(AopSortConstant.Auth_Injection_AOP)
class RequestAop {

    private val log = this.log()

    /**
     * 以ApiOperation为切入点
     */
    @Pointcut(value = "execution(public * xyz.labmem..*.controller.*.*(..))")
    fun HttpInfo() {}

    /**
     * ControllerHttp请求日志
     */
    @Around("HttpInfo()")
    @Throws(Throwable::class)
    fun info(pjp: ProceedingJoinPoint): Any? {
        val sra = RequestContextHolder.getRequestAttributes() as ServletRequestAttributes?
        var init = 0L
        var uri: String? = null
        if (Objects.nonNull(sra)) {
            init = System.currentTimeMillis()
            val request = sra!!.request
            uri = request.requestURI
            val method = request.method
            log.info("|>>>>> 请求IP地址:[${request.getIp()}];请求URI: '${uri}'; " + method)
        }
        val `object` = pjp.proceed()
        if (Objects.nonNull(sra)) {
            val request = sra!!.request
            val over = System.currentTimeMillis() - init
            log.info(
                "|<<<<< 响应IP地址:[${request.getIp()}];响应URI: '${uri}'  共耗时：$over ms "
            )
        }
        return `object`
    }


}